package com.xwj.producer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

/**
 * @author xwj
 * @date 2020/3/26
 */
@Component
public class KafkaProducer {
    private static Logger logger = LoggerFactory.getLogger(KafkaProducer.class);
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    /**
     * 发送消息
     *
     * @param topic
     * @param value
     */
    public void send(String topic, Object value) {
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, value);
        future.addCallback(success -> { logger.info("producer成功发送消息:{},->{}", value.toString(), topic); },
                error -> { logger.error("producer发送消息:{},失败:{}", value.toString(), error.getMessage());
                });
    }

    /**
     * 发送消息
     *
     * @param topic
     * @param key
     * @param value
     */
    public void send(String topic, String key, Object value) {
        ListenableFuture<SendResult<String, Object>> future = kafkaTemplate.send(topic, key, value);
        future.addCallback(success -> { logger.info("producer成功发送消息:{},->{}", value.toString(), topic); },
                error -> { logger.error("producer发送消息:{},失败:{}", value.toString(), error.getMessage());
        });
    }
}
